<template>
  <el-card class="box-card">
    <div slot="header" class="clearfix">
      <span>基本资料</span>
    </div>
    <!-- 表单 -->
    <el-form
      :model="userForm"
      :rules="UserRules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="用户名称" prop="username">
        <el-input v-model="userForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button @click="updateUserInfo" type="primary">立即修改</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: "UserInfo",
  methods: {
    resetForm() {
      // 使用浅拷贝vuex里面的数据拷贝到新的对象中,将新的对象的值提交给formData
      this.userForm = { ...this.$store.state.userInfo };
    },
    updateUserInfo() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "/my/userinfo",
          this.userForm
        );
        // console.log(res);
        if (res.code !== 0) return this.$message.error(res.message);
        this.$message.success(res.message);
        // 2.3 更新vuex中的数据
        this.$store.dispatch("initUserInfo");
      });
    },
  },
  data() {
    return {
      userForm: { ...this.$store.state.userInfo },
      UserRules: {
        nickname: [
          { required: true, message: "请输入昵称", trigger: "blur" },
          {
            pattern: /^\S[a-zA-Z0-9]{1,10}$/,
            message: "用户名必须是1-10位的非空字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
};
</script>

<style lang="less" scoped>
.el-form {
  width: 500px;
}
</style>
